//
//  RecommendViewController.m
//  OverseasOnlineShopping
//
//  Created by 唐先才 on 16/3/7.
//  Copyright © 2016年 唐先才. All rights reserved.
//

#import "RecommendViewController.h"
#import "AFNetworking.h"
#import "TxcPrefixHeader.pch"
#import "TxcModel.h"
#import "BaseCollectionViewCell.h"
#import "OverseasOnlineShopping-swift.h"
#import "MJRefresh.h"
#import "MJRefreshHeader.h"
#import "MJRefreshFooter.h"
#import "SepcialDetailViewController.h"
#import "SVProgressHUD.h"

@interface RecommendViewController()
{
    UICollectionView *_collectionView;
    UICollectionReusableView *_head;
    NSMutableArray *_dataArray1;
    NSMutableArray *_dataArray2;
    NSMutableArray *_dataArray3;
    NSMutableArray *_dataArray4;
    NSInteger _page;
    BOOL _isPulling;
    BOOL isAnimation;
    CGFloat lastContentOffsetY;
    UICollectionViewFlowLayout *_layout;
    WaitLoadView *_waitView;
    
}

@end

@implementation RecommendViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    _dataArray1 = [[NSMutableArray alloc] init];
    _dataArray2 = [[NSMutableArray alloc] init];
    _dataArray3 = [[NSMutableArray alloc] init];
    _dataArray4 = [[NSMutableArray alloc] init];
    _page = 1;
    isAnimation = NO;
    lastContentOffsetY = 0;
    [self createData];
    [self createCollectionView];
    [self createRefresh];
    _waitView = [[WaitLoadView alloc] initWithFrame:self.view.frame];
    [self.view addSubview: _waitView];
}

- (void)createCollectionView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    _layout = layout;
    _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    [self.view addSubview:_collectionView];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.backgroundColor = [UIColor colorWithRed:239 / 255.0 green:239 / 255.0 blue:239 / 255.0 alpha:1.0];
    
    UINib *nib1 = [UINib nibWithNibName: @"ButtonCell" bundle: [NSBundle mainBundle]];
    [_collectionView registerNib:nib1 forCellWithReuseIdentifier: @"buttonCell"];
    UINib *nib2 = [UINib nibWithNibName: @"SpecialCell" bundle: [NSBundle mainBundle]];
    [_collectionView registerNib:nib2 forCellWithReuseIdentifier: @"specialCell"];
    UINib *nib3 = [UINib nibWithNibName: @"BaseCollectionViewCell" bundle: [NSBundle mainBundle]];
    [_collectionView registerNib:nib3 forCellWithReuseIdentifier: @"baseCollectionViewCell"];
    [_collectionView registerClass:[CollectionHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"_head"];
    [_collectionView registerClass:[ButtonView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"button"];
}

- (void)createData {
    [_dataArray1 removeAllObjects];
    [_dataArray2 removeAllObjects];
    [_dataArray3 removeAllObjects];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    /*
     头视图
     */
    NSDictionary *parameters1 = @{@"infoNation": @"0",
                                  @"mallUrl": @""
                                  };
    [manager POST:ScrollerView_URL parameters:parameters1 success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSArray *array1 = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        for (NSDictionary *dict1 in array1) {
            TxcModel *model = [TxcModel modelWithDict:dict1];
            [_dataArray1 addObject:model];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus: AppNetErrorTips];
    }];

    /*
     button图
     */
    [manager POST:BUTTON_URL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSArray *array2 = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        for (NSDictionary *dict2 in array2) {
            TxcModel *model = [TxcModel modelWithDict:dict2];
            [_dataArray2 addObject:model];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus: AppNetErrorTips];
    }];
    
    /*
     专题视图
     */
    NSDictionary *parameters3 = @{@"p_btSpecialType": @"0",
                                  @"p_iPageIndex": @"1",
                                  @"p_iPageSize": @"5",
                                  @"p_iParentSpecialID": @"0",
                                  };
    [manager POST:ZHUANTI_URL parameters:parameters3 success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSArray *array3 = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        for (NSDictionary *dict3 in array3) {
            TxcModel *model = [TxcModel modelWithDict:dict3];
            [_dataArray3 addObject:model];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus: AppNetErrorTips];
    }];

    /*
     排列视图
     */
    NSString *page = [NSString stringWithFormat:@"%ld", (long)_page];
    NSDictionary *parameters4 = @{@"brightUrl": @"",
                                  @"catUrl": @"",
                                  @"exceptMallUrl": @"",
                                  @"homeShow": @"1",
                                  @"infoNation": @"0",
                                  @"infoType": @"0",
                                  @"isTop": @"1",
                                  @"keyWord": @"",
                                  @"mallUrl": @"",
                                  @"pageIndex": page,
                                  @"pageSize": @"20",
                                  @"tagUrl": @"",
                                  };
    [manager POST:HOMEPAGE_URL parameters:parameters4 success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [_waitView removeFromSuperview];
        NSArray *array4 = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        for (NSDictionary *dict4 in array4) {
            TxcModel *model = [TxcModel modelWithDict:dict4];
            [_dataArray4 addObject:model];
        }
        [_collectionView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus: AppNetErrorTips];
    }];
    
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 3;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 0) {
        return _dataArray2.count;
    } else if (section == 1) {
        return _dataArray3.count;
    }
    return _dataArray4.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return [ButtonCell buttonCellWithCollectionView:collectionView dataArray:_dataArray2 indexPath:indexPath];
    } else if (indexPath.section == 1) {
        return [SpecialCell specialCellWithCollectionView:collectionView dataArray:_dataArray3 indexPath:indexPath];
    }
    return [BaseCollectionViewCell configCellWith:collectionView indexPath:indexPath dataArray:_dataArray4];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
//        _layout.minimumLineSpacing = 0;
        _layout.minimumInteritemSpacing = 0;
        return CGSizeMake((SCREEN_WIDTH - 4) / 4, 80);
    } else if (indexPath.section == 1) {
        return CGSizeMake(SCREEN_WIDTH, 360);
    }
    return CGSizeMake((SCREEN_WIDTH - 20) / 2, 320);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return CGSizeMake(SCREEN_WIDTH, 200);
    } else if (section == 2) {
        return CGSizeMake(SCREEN_WIDTH, 140);
    }
    return CGSizeZero;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    if (section == 2) {
        return UIEdgeInsetsMake(10, 5, 10, 5);
    }
    return UIEdgeInsetsZero;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && kind == UICollectionElementKindSectionHeader) {
        CollectionHeaderView *collectionHeadView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"_head" forIndexPath:indexPath];
        [collectionHeadView passDataArray:_dataArray1];
        return collectionHeadView;
    } else if (indexPath.section == 2 && kind == UICollectionElementKindSectionHeader) {
        ButtonView *buttonView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"button" forIndexPath:indexPath];
        return buttonView;
    }
    return nil;
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section != 2) {
        return;
    }
    if (isAnimation) {
        [self startAnimation:cell offsetY:120 duration:1.0];
    }
}


- (void)startAnimation: (UIView *)view offsetY: (CGFloat)offsetY duration: (NSTimeInterval)duration {
    view.transform = CGAffineTransformMakeTranslation(0, offsetY);
    [UIView animateWithDuration:duration animations:^{
        view.transform = CGAffineTransformIdentity;
    }];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y <= scrollView.contentSize.height) {
        isAnimation = lastContentOffsetY < scrollView.contentOffset.y;
        lastContentOffsetY = scrollView.contentOffset.y;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            SepcialDetailViewController * sepcialDetailVC = [[SepcialDetailViewController alloc] init];
            [self.viewController.navigationController pushViewController:sepcialDetailVC animated:YES];
        } else if (indexPath.row == 1) {
            HeadlinesViewController *headlinesVC = [[HeadlinesViewController alloc] init];
            [self.viewController.navigationController pushViewController:headlinesVC animated:YES];
        } else if (indexPath.row == 2) {
            InfomationViewController *infomationVC = [[InfomationViewController alloc] init];
            [self.viewController.navigationController pushViewController:infomationVC animated:YES];
        } else if (indexPath.row == 3) {
            FindViewController *findVC = [[FindViewController alloc] init];
            [self.viewController.navigationController pushViewController:findVC animated:YES];
        }
    } else if (indexPath.section == 1) {
        
    } else if (indexPath.section == 2) {
        TxcModel *model = _dataArray4[indexPath.row];
        DetailViewController *detailVC = [[DetailViewController alloc] init];
        NSString *infoID = [NSString stringWithFormat:@"%@", model.InfoID];
        detailVC.goodsID = infoID;
        detailVC.parameters = @{@"infoID": infoID};
        detailVC.pic_url = model.MainImage;
        [self.viewController.navigationController pushViewController:detailVC animated:YES];
    }
}

//- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//    CGFloat offset = _collectionView.contentOffset.y;
//    if (offset > SCREEN_HEIGHT * 2 / 3) {
//        _collectionView.backgroundColor = [UIColor colorWithRed:239 / 255.0 green:239 / 255.0 blue:239 / 255.0 alpha:1.0];
//    }
//}

- (void)createRefresh {
    _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downRefresh)];
    _collectionView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(upRefresh)];
}

- (void)downRefresh {
    _isPulling = YES;
    [_collectionView.mj_header beginRefreshing];
    [self createData];
    [_collectionView.mj_header endRefreshing];
}

- (void)upRefresh {
    _isPulling = NO;
    _page ++;
    [_collectionView.mj_footer beginRefreshing];
    [self createData];
    [_collectionView.mj_footer endRefreshing];
}

@end
